// 用户认证状态管理
import { defineStore } from 'pinia'
import { ref, computed, readonly } from 'vue'
import type { User, LoginRequest, RegisterRequest, AuthState } from '@/types'
import { userAPI, sessionAPI } from '@/services/api'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const isAuthenticated = computed(() => !!user.value && !!token.value)
  const isAdmin = computed(() => user.value?.role === 'admin')
  const isStudent = computed(() => user.value?.role === 'student')

  // 从本地存储恢复状态
  const restoreAuth = () => {
    try {
      const savedUser = localStorage.getItem('auth_user')
      const savedToken = localStorage.getItem('auth_token')
      
      if (savedUser && savedToken) {
        user.value = JSON.parse(savedUser)
        token.value = savedToken
      }
    } catch (error) {
      console.error('Failed to restore auth state:', error)
      clearAuth()
    }
  }

  // 保存认证状态到本地存储
  const saveAuth = (userData: User, userToken: string) => {
    try {
      localStorage.setItem('auth_user', JSON.stringify(userData))
      localStorage.setItem('auth_token', userToken)
      user.value = userData
      token.value = userToken
    } catch (error) {
      console.error('Failed to save auth state:', error)
    }
  }

  // 清除认证状态
  const clearAuth = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('auth_user')
    localStorage.removeItem('auth_token')
  }

  // 登录
  const login = async (credentials: LoginRequest): Promise<boolean> => {
    isLoading.value = true
    error.value = null

    try {
      const response = await userAPI.login(credentials)
      saveAuth(response.user, response.token)
      return true
    } catch (err) {
      error.value = err instanceof Error ? err.message : '登录失败，请重试'
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 注册
  const register = async (userData: RegisterRequest): Promise<boolean> => {
    isLoading.value = true
    error.value = null

    try {
      // 验证密码确认
      if (userData.password !== userData.confirmPassword) {
        error.value = '密码确认不匹配'
        return false
      }

      // 创建用户
      const { confirmPassword, ...userDataWithoutConfirm } = userData
      const response = await userAPI.register(userDataWithoutConfirm)
      
      // 自动登录
      saveAuth(response.user, response.token)
      return true
    } catch (err) {
      error.value = err instanceof Error ? err.message : '注册失败，请重试'
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 登出
  const logout = async () => {
    isLoading.value = true
    
    try {
      // 如果有会话token，尝试删除服务器端会话
      if (token.value && user.value) {
        // 这里可以添加删除服务器端会话的逻辑
        // 由于json-server的限制，我们暂时只清除本地状态
      }
    } catch (err) {
      console.error('Logout error:', err)
    } finally {
      clearAuth()
      isLoading.value = false
    }
  }

  // 更新用户信息
  const updateProfile = async (profileData: Partial<User>): Promise<boolean> => {
    if (!user.value) return false

    isLoading.value = true
    error.value = null

    try {
      const updatedUser = await userAPI.updateUser(user.value.id, profileData)
      user.value = updatedUser
      localStorage.setItem('auth_user', JSON.stringify(updatedUser))
      return true
    } catch (err) {
      error.value = err instanceof Error ? err.message : '更新失败，请重试'
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  // 初始化时恢复认证状态
  restoreAuth()

  return {
    // 状态
    user: readonly(user),
    token: readonly(token),
    isLoading: readonly(isLoading),
    error: readonly(error),
    
    // 计算属性
    isAuthenticated,
    isAdmin,
    isStudent,
    
    // 方法
    login,
    register,
    logout,
    updateProfile,
    clearError,
    restoreAuth,
    saveAuth,
  }
})